package vaccine.appointment.system.appointmentrecord.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import vaccine.appointment.system.appointmentrecord.service.AppointmentRecordService;
import vaccine.appointment.system.appointmentrecord.vo.AppointmentCalendarDayVO;
import vaccine.appointment.system.appointmentrecord.vo.TodayAppointmentVO;
import vaccine.appointment.system.appointmentrecord.vo.UpdateAppointmentStatusRequest;
import vaccine.appointment.system.common.annotation.AutoWrapResult;
import vaccine.appointment.system.common.annotation.RequireRole;
import vaccine.appointment.system.user.dataobject.User;
import vaccine.appointment.system.user.enums.IdentityInfoEnum;
import vaccine.appointment.system.user.mapper.UserMapper;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;

/**
 * 管理员预约控制器
 */
@AutoWrapResult
@RequestMapping("/admin/appointment")
@RestController
@RequireRole({IdentityInfoEnum.HOSPITAL_ADMIN, IdentityInfoEnum.SUPER_ADMIN})
public class AdminAppointmentController {

    @Autowired
    private AppointmentRecordService appointmentRecordService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询当日预约列表
     * @param status 预约状态（可选）
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param httpRequest HTTP请求
     * @return 分页数据
     */
    @GetMapping("/today")
    public Page<TodayAppointmentVO> getTodayAppointments(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            HttpServletRequest httpRequest) {
        Integer vaccinationSiteId = resolveVaccinationSiteId(httpRequest);
        return appointmentRecordService.getTodayAppointments(vaccinationSiteId, status, pageNum, pageSize);
    }

    /**
     * 查询指定日期的预约列表
     */
    @GetMapping("/by-date")
    public List<TodayAppointmentVO> getAppointmentsByDate(
            @RequestParam(required = false) String date,
            HttpServletRequest httpRequest) {
        Integer vaccinationSiteId = resolveVaccinationSiteId(httpRequest);
        LocalDate targetDate = StringUtils.hasText(date) ? LocalDate.parse(date) : LocalDate.now();
        return appointmentRecordService.getAppointmentsByDate(vaccinationSiteId, targetDate);
    }

    /**
     * 查询月份预约汇总
     */
    @GetMapping("/calendar")
    public List<AppointmentCalendarDayVO> getCalendarSummary(
            @RequestParam(required = false) String month,
            HttpServletRequest httpRequest) {
        Integer vaccinationSiteId = resolveVaccinationSiteId(httpRequest);
        LocalDate targetMonth = StringUtils.hasText(month)
                ? YearMonth.parse(month).atDay(1)
                : LocalDate.now().withDayOfMonth(1);
        return appointmentRecordService.getMonthlySummary(vaccinationSiteId, targetMonth);
    }

    /**
     * 更新预约状态
     * @param appointmentId 预约ID
     * @param request 更新状态请求
     * @param httpRequest HTTP请求
     * @return 是否成功
     */
    @PutMapping("/{appointmentId}/status")
    public Boolean updateAppointmentStatus(
            @PathVariable Integer appointmentId,
            @Valid @RequestBody UpdateAppointmentStatusRequest request,
            HttpServletRequest httpRequest) {
        Integer vaccinationSiteId = resolveVaccinationSiteId(httpRequest);
        return appointmentRecordService.updateAppointmentStatus(appointmentId, request.getStatus(), vaccinationSiteId);
    }

    /**
     * 获取当前用户可查看的接种点ID（普通管理员查看全部）
     */
    private Integer resolveVaccinationSiteId(HttpServletRequest httpRequest) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        User user = userMapper.selectById(userId);

        if (user != null && user.getIdentityInfo().equals(IdentityInfoEnum.HOSPITAL_ADMIN.getCode())) {
            return user.getVaccinationSiteId();
        }
        return null;
    }
}

